<template>
  <el-dialog v-model="dialogVisible" title="选择菜品">
    <div style="margin-top: -20px; margin-bottom: 10px">
      <el-input v-model="searchKw" placeholder="请输入菜品名称或助记码搜索" :prefix-icon="Search" />
    </div>
    <div class="selector-container">
      <TreeFilter
        label="name"
        :show-search="false"
        :data="treeFilterData"
        :default-value="initParam.ctegoryId"
        @change="changeTreeFilter"
      />
      <div class="table-box">
        <el-table ref="tableRef" :data="tableData" @select="handleSelect" @select-all="handleSelectAll">
          <el-table-column type="selection" width="55" />
          <el-table-column property="name" label="菜品名称" />
          <el-table-column property="ctegoryName" label="助记码" />
        </el-table>
      </div>
    </div>
    <div class="selector-footer">
      <div class="flx-justify-between pt10 pb10">
        <span>已选择({{ tags.length }})</span>
        <el-button type="danger" @click="clearSelection">清空</el-button>
      </div>
      <div class="inner">
        <el-tag v-for="tag in tags" :key="tag.id" class="mr6 mb6" closable @close="handleDelTag(tag.id)">
          {{ tag.name }}
        </el-tag>
      </div>
    </div>
    <template #footer>
      <el-button @click="dialogVisible = false"> 取消 </el-button>
      <el-button type="primary" @click="handleSubmit"> 确定 </el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup name="selectGoods">
import { ref, reactive, nextTick } from "vue";
import { Goods } from "@/api/interface";
import { Search } from "@element-plus/icons-vue";
import { ElMessage, ElTable, FormInstance } from "element-plus";
import { getFoodCategoryList, getGoodsList } from "@/api/modules/goods";
import TreeFilter from "@/components/TreeFilter/index.vue";

interface dialogProps {
  isView: boolean;
  row: Partial<Goods.ResGoodsSpecificationsList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}
const tableRef = ref<InstanceType<typeof ElTable>>();
const initParam = reactive({ ctegoryId: null });
const dialogVisible = ref(false);
const treeFilterData = ref<any>([]);
const tableData = ref<Goods.ResGoodsList[]>([]);
// const selectData = ref<Goods.ResGoodsList[]>([]);
const tags = ref<Goods.ResGoodsList[]>([]);
const searchKw = ref("");

const dialogProps = ref<dialogProps>({
  isView: false,
  row: {}
});

// 树形筛选切换
const changeTreeFilter = (val: any) => {
  ElMessage.success("请注意查看请求参数变化!");
  initParam.ctegoryId = val;
  getTableData();
};

// 接收父组件传过来的参数
const acceptParams = (params: dialogProps) => {
  dialogProps.value = params;
  dialogVisible.value = true;
  getTreeFilter();
};

const getTreeFilter = async () => {
  const { data } = await getFoodCategoryList();
  treeFilterData.value = data.list;
  initParam.ctegoryId = null;
  await getTableData();
};

const getTableData = () => {
  getGoodsList({ ...initParam, pageNum: 1, pageSize: 9999 }).then(res => {
    tableData.value = res.data.list ?? [];
    tags.value = [
      {
        id: 1,
        name: "我是名称来的",
        ctegoryName: "助记码",
        price: 400,
        goodsStatus: 1
      },
      {
        id: 2,
        name: "我是名称来的",
        ctegoryName: "助记码",
        price: 400,
        goodsStatus: 1
      },
      {
        id: 3,
        name: "我是名称来的",
        ctegoryName: "助记码",
        price: 400,
        goodsStatus: 1
      },
      {
        id: 4,
        name: "我是名称来的",
        ctegoryName: "助记码",
        price: 400,
        goodsStatus: 1
      },
      {
        id: 5,
        name: "我是名称来的",
        ctegoryName: "助记码",
        price: 400,
        goodsStatus: 1
      }
    ];
    nextTick(() => {
      tableData.value.forEach(item => {
        let result = tags.value.find(row => row.id == item.id);
        if (result) {
          tableRef.value!.toggleRowSelection(item, true);
        }
      });
    });
  });
};

const handleDelTag = (tag?: number | string) => {
  let index1 = tags.value.findIndex(item => item.id === tag);
  let index2 = tableData.value.findIndex(item => item.id === tag);
  if (index1 > -1) {
    tags.value.splice(index1, 1);
  }
  if (index2 > -1) {
    tableRef.value!.toggleRowSelection(tableData.value[index2], false);
  }
};
// 全选 反选
const handleSelectAll = (selection: Goods.ResGoodsList[]) => {
  if (selection.length === 0) {
    tags.value = tags.value.filter(item2 => {
      return tableData.value.every(item1 => item1.id !== item2.id);
    });
  } else {
    tags.value = [...tags.value, ...tableData.value.filter(item1 => !tags.value.find(item2 => item2.id === item1.id))];
  }
};

// 选中 取消
const handleSelect = (selection?: Goods.ResGoodsList[], row?: any) => {
  let index = tags.value.findIndex(item => item.id === row.id);
  if (index > -1) {
    tags.value.splice(index, 1);
  } else {
    tags.value.push(row);
  }
};

// 清空选择
const clearSelection = () => {
  if (tags.value.length !== 0) {
    tags.value.splice(0, tags.value.length);
    tableRef.value!.clearSelection();
  }
};

// 提交数据（选择菜品）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      await dialogProps.value.api!(dialogProps.value.row);
      ElMessage.success({ message: `选择菜品成功！` });
      dialogProps.value.getTableList!();
      dialogVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({
  acceptParams
});
</script>
